package com.ruoyi.web.controller.ora;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.KeyValidate;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.dict.*;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.ora.domain.AssetsRecycle;
import com.ruoyi.ora.domain.Device;
import com.ruoyi.ora.domain.DeviceUser;
import com.ruoyi.ora.domain.VoiceRecord;
import com.ruoyi.ora.service.IAssetsRecycleService;
import com.ruoyi.ora.service.IDeviceService;
import com.ruoyi.ora.service.IDeviceUserService;
import com.ruoyi.ora.service.IVoiceRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 语音转写记录Controller
 * 
 * @author liuwp
 * @date 2024-11-14
 */
@RestController
@RequestMapping("/ora/voice_record")
public class VoiceRecordController extends BaseController
{
    @Autowired
    private IVoiceRecordService voiceRecordService;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IDeviceUserService deviceUserService;
    @Autowired
    private IAssetsRecycleService assetsRecycleService;

    /**
     * 查询语音转写记录列表
     */
    @PreAuthorize("@ss.hasPermi('ora:voice_record:list')")
    @GetMapping("/list")
    public TableDataInfo list(VoiceRecord voiceRecord)
    {
        startPage();
        List<VoiceRecord> list = voiceRecordService.selectVoiceRecordList(voiceRecord);
        return getDataTable(list);
    }

    /**
     * 导出语音转写记录列表
     */
    @PreAuthorize("@ss.hasPermi('ora:voice_record:export')")
    @Log(title = "语音转写记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, VoiceRecord voiceRecord)
    {
        List<VoiceRecord> list = voiceRecordService.selectVoiceRecordList(voiceRecord);
        ExcelUtil<VoiceRecord> util = new ExcelUtil<VoiceRecord>(VoiceRecord.class);
        util.exportExcel(response, list, "语音转写记录数据");
    }

    /**
     * 获取语音转写记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('ora:voice_record:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        VoiceRecord voiceRecord = voiceRecordService.selectVoiceRecordById(id);
        if (voiceRecord != null){
            voiceRecord.setReadStatus(SysYesNo.YES.getValue());
            voiceRecordService.updateVoiceRecord(voiceRecord);
        }
        return AjaxResult.success(voiceRecord);
    }

    /**
     * 新增语音转写记录
     */
    @PreAuthorize("@ss.hasPermi('ora:voice_record:add')")
    @Log(title = "语音转写记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody VoiceRecord voiceRecord)
    {
        return toAjax(voiceRecordService.insertVoiceRecord(voiceRecord));
    }

    /**
     * 修改语音转写记录
     */
    @PreAuthorize("@ss.hasPermi('ora:voice_record:edit')")
    @Log(title = "语音转写记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody VoiceRecord voiceRecord)
    {
        VoiceRecord voiceRecord1 = voiceRecordService.selectVoiceRecordById(voiceRecord.getId());
        if (voiceRecord1 != null && StringUtils.isNotEmpty(voiceRecord1.getVoiceTransliterate()) && StringUtils.isNotEmpty(voiceRecord.getVoiceContent())){
            JSONObject jsonObject = JSONObject.parseObject(voiceRecord1.getVoiceTransliterate());
            jsonObject.put("text", voiceRecord.getVoiceContent());
            voiceRecord.setVoiceTransliterate(jsonObject.toJSONString());
        }
        return toAjax(voiceRecordService.updateVoiceRecord(voiceRecord));
    }

    /**
     * 删除语音转写记录
     */
    @PreAuthorize("@ss.hasPermi('ora:voice_record:remove')")
    @Log(title = "语音转写记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        int delCount = 0;
        for (Long id : ids) {

            int result = voiceRecordService.updateVoiceRecord(Builder.of(VoiceRecord::new).with(VoiceRecord::setId, id).with(VoiceRecord::setDeleteTime, new Date()).build());
            delCount += result;
            if (result > 0) {
                // 添加到回收站
                assetsRecycleService.insertAssetsRecycle(Builder.of(AssetsRecycle::new)
                        .with(AssetsRecycle::setAssetsType, AssetsType.VOICE.getValue())
                        .with(AssetsRecycle::setAssetsId, id)
                        .with(AssetsRecycle::setUserId, SecurityUtils.getUserId())
                        .build());
            }

        }
        return toAjax(delCount);
//        return toAjax(voiceRecordService.deleteVoiceRecordByIds(ids));
    }


    //  TODO   转写记录和创建转写两个接口  还有转写任务调用


    @PreAuthorize("@ss.hasPermi('ora:voice_record:list')")
    @GetMapping("/query")
    public TableDataInfo query(VoiceRecord voiceRecord)
    {
//        voiceRecord.setStatus(VoiceRecordStatus.TRANSLATED.getValue());
        if (voiceRecord.getVoiceType().intValue() == VoiceRecordType.APP_RECORDING.getValue()){
            voiceRecord.setUserId(SecurityUtils.getUserId());
        }else {
            if (voiceRecord.getDeviceId() == null){
                return getDataTable(new ArrayList<VoiceRecord>());
            }
        }

        List<VoiceRecord> list = null;

        if (voiceRecord.getShowType() != null && voiceRecord.getShowType().intValue() == AssetsShowType.COLLECTION.getValue().intValue()){
            voiceRecord.setUserId(SecurityUtils.getUserId());
            startPage();
            list = voiceRecordService.selectVoiceRecordListCollection(voiceRecord);
        }else {
            boolean isAdmin = false;

            // 要先判断自己的权限
            if (voiceRecord.getDeviceId() != null){
                DeviceUser deviceUser = deviceUserService.selectOneDeviceUser(Builder.of(DeviceUser::new)
                        .with(DeviceUser::setUserId, SecurityUtils.getUserId())
                        .with(DeviceUser::setDeviceId, voiceRecord.getDeviceId())
                        .build());

                if (deviceUser == null){
                    return getDataTable(new ArrayList<VoiceRecord>());
                }
                voiceRecord.setDeviceUserId(deviceUser.getId());
                if (deviceUser.getDevicePermission().intValue() == DevicePermission.ADMIN.getValue().intValue()){
                    isAdmin = true;
                }
            }

            if (!isAdmin && voiceRecord.getShowType() != null && voiceRecord.getShowType().intValue() == AssetsShowType.PARTABLE.getValue().intValue()){
                startPage();
                list = voiceRecordService.selectVoiceRecordListDeviceUser(voiceRecord);
            }else {
                startPage();
                list = voiceRecordService.selectVoiceRecordList(voiceRecord);
            }
        }

        list.forEach(item->{
            if (item.getStatus().intValue() == VoiceRecordStatus.TRANSLATING.getValue()){
                item.setVoiceContent(MessageUtils.message("ora.voice.translating"));
            }else if (item.getStatus().intValue() == VoiceRecordStatus.ERROR.getValue()){
                item.setVoiceContent(MessageUtils.message("ora.voice.error"));
            }
        });
        // TODO 添加一个默认语音
        list.add(voiceRecordService.selectVoiceRecordById(1L));
        return getDataTable(list);
    }

//    @PreAuthorize("@ss.hasPermi('ora:voice_record:add')")
    @Log(title = "APP录音", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    public AjaxResult upload(VoiceRecord voiceRecord, MultipartFile file)
    {
        if (file != null){
            voiceRecord.setUserId(SecurityUtils.getUserId());
            voiceRecord.setVoiceType(VoiceRecordType.APP_RECORDING.getValue());
            return AjaxResult.success(voiceRecordService.voiceRecordUpload(voiceRecord, file));
        }else {
            return AjaxResult.error(MessageUtils.message("ora.voice.notnull"));
        }
    }

    @Log(title = "设备录音", businessType = BusinessType.INSERT)
    @PostMapping("/device")
    @KeyValidate()
    public AjaxResult device(VoiceRecord voiceRecord, MultipartFile file)
    {
        if (file != null){
            if (StringUtils.isNotEmpty(voiceRecord.getDeviceSn())){
                Device device = deviceService.selectOneDevice(Builder.of(Device::new).with(Device::setDeviceSn, voiceRecord.getDeviceSn()).build());
                if (device != null){
                    voiceRecord.setDeviceId(device.getId());
                    voiceRecord.setVoiceType(VoiceRecordType.DEVICE_RECORDING.getValue());
                    return AjaxResult.success(voiceRecordService.voiceRecordUpload(voiceRecord, file));
                }else {
                    return AjaxResult.error(MessageUtils.message("ora.device.notexist"));
                }
            }else {
                return AjaxResult.error(MessageUtils.message("ora.common.required"));
            }
        }else {
            return AjaxResult.error(MessageUtils.message("ora.voice.notnull"));
        }
    }

    @Log(title = "通话录音", businessType = BusinessType.INSERT)
    @PostMapping("/call")
    @KeyValidate()
    public AjaxResult call(VoiceRecord voiceRecord, MultipartFile file)
    {
        if (file != null){
            if (StringUtils.isNotEmpty(voiceRecord.getDeviceSn())){
                Device device = deviceService.selectOneDevice(Builder.of(Device::new).with(Device::setDeviceSn, voiceRecord.getDeviceSn()).build());
                if (device != null){
                    voiceRecord.setDeviceId(device.getId());
                    voiceRecord.setVoiceType(VoiceRecordType.CALL_RECORDING.getValue());
                    return AjaxResult.success(voiceRecordService.voiceRecordUpload(voiceRecord, file));
                }else {
                    return AjaxResult.error(MessageUtils.message("ora.device.notexist"));
                }
            }else {
                return AjaxResult.error(MessageUtils.message("ora.common.required"));
            }
        }else {
            return AjaxResult.error(MessageUtils.message("ora.voice.notnull"));
        }
    }


    @Log(title = "语音文件移动", businessType = BusinessType.INSERT)
    @PostMapping("/movie")
    public AjaxResult voiceMovie(@RequestBody VoiceRecord voiceRecord)
    {
        if (voiceRecord.getVoiceFolderId() != null && voiceRecord.getId() != null){
            return toAjax(voiceRecordService.updateVoiceRecord(voiceRecord));
        }else {
            return AjaxResult.error(MessageUtils.message("ora.common.required"));
        }
    }

    public static void main(String[] args) {
        System.out.println(Md5Utils.hash("oramemo123998877"));
    }
}
